package com.javayh.comsumer;

import com.javayh.entity.Order;
import org.springframework.amqp.AmqpApplicationContextClosedException;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
import com.rabbitmq.client.*;

import java.util.Map;

/**
 * @author Dylan Yang
 * @Title: OrderReceiver
 * @ProjectName lucky
 * @Description: TODO
 * @date 2018/10/512:07
 */
@Component
public class OrderReceiver {

    /**
      * mq消费端
      *  RabbitHandler  标识
      * @author Dylan Yang
      */
    @RabbitHandler
    @RabbitListener(
            bindings = @QueueBinding(value = @Queue(value = "order-queues",durable = "true"),
            exchange = @Exchange(value = "order-exchange",durable = "true",type = "topic"),
                    key = "order.#"
            )
    )
    public void onOrderMessage(@Payload Order order,
                               @Headers Map<String,Object> headers,
                               Channel channel){
        //消费者操作
        System.out.println("----------收到消息，开始消费---------");
        System.out.println("订单ID ---> " +order.getId());
        Long delivery = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        //ACK
        try{
            channel.basicAck(delivery,false);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("异常消息"+e.getMessage());
        }
    }

}

